<?php
class Macys_Oauth_Authenticate_Code extends Macys_Oauth_Authenticate_BaseAuth {

	
	protected $_args = null;
	protected $_code = null;

	//protected $_auth_endpoint = "/v2/oauth2/authorize";
	protected $_auth_endpoint = "/authorize";

	// Mashery Endpoint used for authorization_code or refresh_token
	protected $_access_token_uri = "/token";

	public function __construct($config) {

		if($config instanceof Zend_Config) {
			$config = $config->toArray();
		}

		if (isset($config['mashery_uri'])) {
	 	$this->_mashery_uri = $config['mashery_uri'];
	 	unset($config['mashery_uri']);
		} else {
	 	throw new Zend_Auth_Exception('Required param "mashery_uri" is missing param in config');
		}
		// Calling Parent Constructor to continue initialization process
		parent::__construct($config);
	}

	/**
	 * Set token You have received from Macys / Bloomingdales
	 * @param string $token
	 * @return Macys_Oauth_Authenticate_Code
	 */
	public function setCode($code)
	{
		$this->_code = $code;
		$this->_args = array(
		Macys_Constants::REDIRECT_URL => $this->getRedirectUri(),
		Macys_Constants::GRANTTYPE => Macys_Constants::AUTHROIZATION_CODE,
            'code'          => $code
		);
		return $this;
	}

	public function setRefreshToken($token) {
		$this->_args = array(
		Macys_Constants::GRANTTYPE => Macys_Constants::REFRESH_TOKEN,
		Macys_Constants::REFRESH_TOKEN          => $token,
		);

		return $this;
	}

	/**
	 * Exchange token to access_token
	 * @return Zend_Auth_Result
	 */
	public function authenticate()
	{
		if (empty($this->_args)) {
			$code = Zend_Auth_Result::FAILURE_CREDENTIAL_INVALID;
			return new Zend_Auth_Result($code, false, 'Set Code / refreshToken for authorization');
		}
		$url = $this->_mashery_uri . $this->_access_token_uri;

		$response = $this->_apiCall($url, $this->_args);
		// Sets the Zend_Auth params
		$result = $this->setAuthentication($response);

		return $result;
	}



	/**
	 * Setting the AuthType to Code Flow
	 * @see Macys_Oauth_Authenticate_BaseAuth::setAuthType()
	 */
	protected function setAuthType($type='code') {
		$this->_authType = $type;
	}


}